/** 
 * Creator:     JYW
 * CreatDate:   2019-04-02
 * descripts：  床位图特殊区域组件
*/
import React, { Component } from 'react';
import { Row, Col, message, Menu, Tooltip, Badge } from 'antd';
import { $http } from '../../../containers/config/https';
import TransLoc from '../Trans/TransLoc';
import './CSS/bedchart.less';

const SubMenu = Menu.SubMenu;
let user;
class WaitRooms extends Component {
	constructor(props) {
		super(props);
		user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
		this.state = {
			RoomList: [],
			Patients: [],
			clickRoomCode: '',
			buttonDis: false,
			transVisible: false,
			openKeys: [],
			patientNumber: '',
			admID: '',
			groupDesc: user.groupDesc
		};
	}

	componentDidMount() {
		this.getRooms();
		this.props.onRef(this);
	}

	componentWillUnmount() {
		this.setState = (state, callback) => {
			return;
		};
	}

	getRooms = () => {
		let data = {
			params: [
				{
					hospID: user.hospID,
					type: '',
					wardID: this.props.getData().locID
				}
			]
		};
		$http.post('urlDeault', this, {
			code: '04020001',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					let openKeys = this.state.openKeys;
					if (res.result.length > 0 && openKeys.length == 0) {
						openKeys.push(res.result[0].code);
					}
					this.setState(
						{
							RoomList: res.result,
							openKeys: openKeys
						},
						() => {
							if (res.result.length > 0) {
								this.getPatients(openKeys[0], '1');
							}
						}
					);
				}
			}
		});
	};

	getPatients = (roomCode, flag) => {
		let data = {
			params: [
				{
					wardID: this.props.getData().locID,
					roomType: roomCode
				}
			]
		};
		$http.post('urlDeault', this, {
			code: '04020002',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					this.setState({
						Patients: res.result,
						clickRoomCode: roomCode,
						patientNumber: res.result.length + ''
					});
					setTimeout(() => {
						if (flag == '1') {
							this.props.updateData({
								roomLoading: false,
								selectBedID: '',
								mouseInID: '',
								admID: '',
								patID: '',
								patStatus: ''
							});
						} else {
							this.props.updateData({
								roomLoading: false,
								waitroomsloading: false
							});
						}
					}, 100);
					this.setState({
						admID: ''
					});
				}
			}
		});
	};

	onCardClick = (key, domEvent) => {
		this.getPatients(key.key, '1');
	};

	componentWillReceiveProps(nextProps) {
		if (this.props.roomLoading !== nextProps.roomLoading) {
			if (nextProps.roomLoading) {
				this.getPatients(this.state.clickRoomCode, '1');
			}
		}
		if (this.props.reloading !== nextProps.reloading) {
			if (nextProps.reloading) {
				this.getPatients(this.state.clickRoomCode, '0');
			}
		}
	}

	MouseEnter = (roomCode) => {
		if (this.state.clickRoomCode !== roomCode) return;
		if (this.props.admID !== '' && this.props.selectBedID !== '') {
			this.setState({
				buttonDis: true
			});
		}
	};

	MouseLeave = (roomCode) => {
		if (this.state.clickRoomCode !== roomCode) return;
		this.setState({
			buttonDis: false
		});
	};

	onRemoveBtnClick = (item, key, keyPath) => {
		if (this.props.admID === '') {
			return;
		}
		if (item.key === 'WaitRoom' || item.key === 'DisWaitRoom') {
			this.leaveBed(item?.key || '');
		} else if (item.key === 'TransOut') {
			//转科
			this.transLoc();
		} else if (item.key === 'DocDis') {
			this.doctorDischarge();
		} else if (item.key === 'NurDis') {
			this.nurseDischarge();
		}
	};

	onPatientClick = (roomCode, e) => {
		let admID = e.key;
		let patID = e.item.props.patid;
		let adminID = e.item.props.adminID;
		let preInFlag = e.item.props.preInFlag;
		let separateBedID = e.item.props.separateBedID; // 预分床分床后的ID
		let preSeparationBedFlag = e.item.props?.selectType || ''; // 预分床标志
		if (preInFlag == "Y") {
			message.info("预住院患者禁止操作")
			return
		}
		if (adminID == undefined) {
			adminID = '';
		}
		let patStatus = 'A';
		if (roomCode === 'DocDis') {
			patStatus = 'D';
		}
		if (roomCode === 'NurDis') {
			patStatus = 'N';
		}
		if (roomCode === 'TransIn') {
			patStatus = 'I';
		}
		if (roomCode === 'TransOut') {
			patStatus = 'O';
		}
		if (roomCode === 'Daytime') {
			patStatus = 'IO';
		}
		if (roomCode === 'Admin') {
			patStatus = 'P';
		}
		if (e.key === this.props.admID) {
			admID = '';
			patStatus = '';
		}
		setTimeout(() => {
			this.props.updateData({
				selectBedID: '',
				mouseInID: '',
				admID: admID,
				patID: patID,
				patStatus: patStatus,
				adminID: adminID,
				separateBedID,
				preSeparationBedFlag
			});
			this.setState({
				buttonDis: false,
				admID: admID
			});
		}, 100);
	};

	/**
		 * 转科操作
		 */
	transLoc = () => {
		this.refs.TransLoc.setState({
			visible: true,
			admID: this.props.admID
		});
		this.refs.TransLoc.getTransInfo();
	};

	/**
		 * 医疗结算，护士不可操作
		 */
	doctorDischarge = () => {
		return;
	};

	/**
		 * 护士办理出院
		 */
	nurseDischarge = () => {
		return;
	};

	/** 离床
		 *  bedId 床位Id,userID 操作用户Id ,admID 患者就诊Id,hospID 医院Id ,transType 转移类型(分床,主管医生,护士),doctorId 主管医生Id,nurseId 护士Id
		 *  status 床位操作类型(预留0 在床1 包床2 离床3)
		 *  transStatus 转床状态(1在用,0不在用)
		 */
	leaveBed = (waitCode) => {
		let data = {
			params: [{
				bedID: '',
				userID: user.userID,
				admID: this.props.admID,
				hospID: user.hospID,
				transType: '1',
				status: '3',
				transStatus: '0',
				code: waitCode
			}]
		};
		$http.post('urlDeault', this, {
			code: '04020003',
			data: data,
			success: (res) => {
				if (+res.errorCode === 0) {
					message.success('移入成功!');
					setTimeout(() => {
						this.props.updateData({
							selectBedID: '',
							mouseInID: '',
							admID: '',
							patID: ''
						});
						this.setState({
							buttonDis: false,
							admID: ''
						});
					}, 100);
					this.getPatients(this.state.clickRoomCode, '1');
					this.props.getPatients();
					this.getRooms();
				}
			}
		});
	}

	onOpenChange = (openKeys) => {
		const latestOpenKey = openKeys.find((key) => this.state.openKeys.indexOf(key) === -1);
		if (openKeys.length === 1) {
			this.setState({ openKeys });
		} else {
			this.setState({
				openKeys: latestOpenKey ? [latestOpenKey] : []
			});
		}
	};

	render() {
		return (
			<div className="waitRoom icon" style={{ height: '100%', width: '100%', overflow: 'hidden' }}>
				<Menu openKeys={this.state.openKeys} onOpenChange={this.onOpenChange} mode="inline">
					{this.state.RoomList.map((room) => {
						return (
							<SubMenu
								style={{
									maxHeight: 'calc(100% - 250px)',
								}}
								key={room.code}
								onTitleClick={this.onCardClick}
								className={this.props.admID != this.state.admID ? 'unSelectedPat' : 'selectedPat'}
								title={
									<span>
										<div
											title={room.title}
											className="bedicon"
											style={{
												float: 'left',
												marginTop: '11px',
												width: room.size + 'px',
												height: room.size + 'px',
												backgroundPosition:
													-((room.position % 10 - 1) * 18) +
													'px' +
													' ' +
													-(parseInt(+room.position / 10) * 18) +
													'px'
											}}
										/>
										<span style={{ paddingLeft: '8px', paddingRight: '7px' }}>
											{room.descripts}
										</span>

										<Badge count={room.number} />
									</span>
								}
							>
								{(room.code === 'WaitRoom' || room.code === 'DisWaitRoom') && this.state.groupDesc.indexOf('护士') > -1 ? ( // WaitRoom - 等候区  DisWaitRoom - 出院等候区
									<Menu.Item className="rw-first-menu-item" key={room.code} onClick={this.onRemoveBtnClick}>
										<div
											style={{
												textAlign: 'center',
												fontWeight: 'bold',
												paddingRight: '32px',
												color: '#42B983',
												width: '100%',
											}}
										>
											移入
										</div>
									</Menu.Item>
								) : (
									''
								)}
								{this.state.Patients.map((patient) => {
									return (
										<Menu.Item
											key={patient.admInfo.admID}
											patid={patient.basicInfo.patID}
											adminID={patient.adminID}
											preInFlag={patient.admInfo.preInFlag}
											separateBedID={patient.admInfo?.admHBBedID || ''}
											selectType={patient?.selectType || ''}
											onClick={this.onPatientClick.bind(this, room.code)}
										>
											<div
												className={
													this.props.admID == patient.admInfo.admID ? (
														'itemSelect'
													) : (
														'unItemSelect'
													)
												}
											>
												<span style={{ marginRight: '24px' }}>
													{patient.basicInfo?.patName || ''}
												</span>
												<span style={{ marginRight: '12px' }}>{patient.basicInfo.patSexDesc}</span>
												<span>{patient.admInfo.admAge}</span>
												{patient.admInfo?.admBedCode ? <span style={{ textAlign: 'right', marginLeft: '12px' }}>
													<Tooltip title={'临时床号：' + (patient.admInfo?.admBedRoom || '') + '-' + (patient.admInfo?.admBedCode || '')}>
														{patient.admInfo?.admBedCode || ''}
													</Tooltip>
												</span> : ''}
											</div>
										</Menu.Item>
									);
								})}
							</SubMenu>
						);
					})}
				</Menu>
				<TransLoc visible={this.state.transVisible} ref="TransLoc" />
			</div>
		);
	}
}
export default WaitRooms;
